<?php

/*

company:tiesh.com
project:common
function: 管理员权限控制

created by: Bach
created date: 2016-02-23
description:

modification v1.01
modified by:
description:

//添加
search($tel)
add($tel,$class)
//设置
set($admin_id,$data)
ultimate($admin_id,$cancel=false)
seal($admin_id)
unseal($admin_id)
//移除
remove($admin_id)
//列表
getlist($filter)
//通用
is($demand)
getSetting($demand,$setting)

 */
namespace app\common\model;
use think\Model;
class Admin extends Model {

    var $chief;
    private $config;
    private $userId;
    private $state_removed = 0;
    private $state_active = 1;
    private $state_sealed = 2;
    private $ultimate;
    private $user;

    function __construct() {
        $user = $this->user = new User;
        //获取user_id
        if (!$this->userId) {
            $userId = $this->userId = $user->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
        //获取配置文件
        $this->chief = $this->isChief();
        $config = getConfig('admin');
        foreach ($config as $k =>$v){
            if(isset($v['second'])){
                foreach ($v['second'] as $kk =>$vv){
                    foreach ($vv as $kkk =>$vvv){
                        $config[$kk][$kkk] = $vvv;
                    }
                }
                unset($config[$k]['second']);
            }
        }
        $this->config = $config;
        $this->isUltimate();
    }
    private function isChief($user_id = 0){
        if(!$user_id) $user_id = $this->userId;
        $chiefs = getConfig('admin_chief');
        return in_array($user_id, $chiefs);
    }

    private function isUltimate($class = null,$user_id = 0) {
        if($this->chief) return true;
        if (!$user_id && !$class && !is_null($this->ultimate)) {
            return $this->ultimate;
        }
        if(!$user_id) $user_id = $this->userId;
        if (!$user_id) {
            return false;
        }
        // $class = pay;
        if ($class) {
            if (is_int($class)) {
                $classId = $class;
            } else {
                $config = $this->config[$class];
                $classId = $config['id'];
                if (!$classId) {
                    return false;
                }
            }
            $where['class'] = $classId;
        }
        $where['ultimate'] = 1;
        $where['state'] = $this->state_active;
        $where['user_id'] = $user_id;
        $res = db('admin')->where($where)->find();
        if ($res) {
            $ultimate = true;
        } else {
            $ultimate = false;
        }
        if (!$class) {
            $this->ultimate = $ultimate;
        }
        return $ultimate;
    }
    private function wechatTag($admin_id,$class){
        $find = db('admin')->where(array('admin_id'=>$admin_id))->find();
        $admin_user_id = $find['user_id'];
        $openid = $this->user->getOpenId($admin_user_id);
        $isUltimate = $this->isChief($admin_user_id) || $this->isUltimate(null,$admin_user_id);
        $wechat = new Wechat;
        if($isUltimate){
            $wechat->tag_user_add('admin',$openid);
            $tag['admin'] = 1;
        }else{
            $wechat->tag_user_remove('admin',$openid);
            $tag['admin'] = 0;
        }
        $config = getConfig('admin');
        foreach ($config as $key => $value) {
            if($class == $value['id']) $class = $key;
        }
        $is = $this->is($class,false,$admin_user_id);
        $tag['is'] = $is;
        if( $is['state'] && !isset($is['chief']) && !isset($is['ultimate']) ){
            $res = $wechat->tag_user_add('admin_'.$class,$openid);
        }else{
            $res = $wechat->tag_user_remove('admin_'.$class,$openid);
        }
        $tag['admin_'.$class] = $res;
        // $tag['openid'];
        return $tag;
    }
    //添加
    function search($tel) {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief && !$this->ultimate) {
            return array('state' => 0, 'errormsg' => '您暂无权限');
        }
        $user = $this->user;
        $res = $user->exist(array('tel' => $tel));
        if (!isset($res['state']) || !$res['state']) {
            return $res;
        }
        $user_id = $res['data']['user_id'];
        $user_info = $user->getInfoById($user_id);
        return array('state' => 1, 'data' => array('info' => $user_info));
    }

    function add($tel, $class) {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$class) {
            return array('state' => 0, 'errormsg' => '请选择权限');
        }
        $classId = null;
        foreach ($this->config as $k =>$v){
            if($v['name'] == $class){
                $classId = $v['id'];
            }
        }
//        $config = $this->config[$class];
//        $classId = $config['id'];
        if (isset($classId) && !$classId) {
            return array('state' => 0, 'errormsg' => 'admin class incorrect');
        }
        if (!$this->chief && !$this->isUltimate($class)) {
            return array('state' => 0, 'errormsg' => '暂无权限');
        }
        //通过tel查找用户是否存在
        $user = $this->user;
        $res = $user->exist(array('tel' => $tel));
        if (!$res['state']) {
            return $res;
        }
        $targetUserId = $res['data']['user_id'];




//        $where[] = "TEL = $tel";
//        $field = array("user_id");
//        $res = M(user)->where($where)->field($field)->find();
//        if(!$res){
//            return array(state=>0,errormsg=>'user not found');
//        }
//        $targetUserId = $res['user_id'];
        //看看是否已经添加了管理员
        $where = array(
            'user_id' => $targetUserId,
            'state' => $this->state_active,
            'class' => $classId,
            );
        $res = db('admin')->where($where)->find();
        if ($res) {
            return array('state' => 0, 'errormsg' => 'admin already exist', 'data' => array('admin_id' => $res['admin_id']));
        }
        $add = array(
            'user_id' => $targetUserId,
            'state' => $this->state_active,
            'class' => $classId,
            'creator' => $this->userId,
            "create_time" => time(),
            );
        $admin_id = db('admin')->insertGetId($add);
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'database add error');
        }
        $tag = $this->wechatTag($admin_id,$class);
        return array('state' => 1, 'tag' => $tag, 'errormsg' => 'admin added', 'data' => array('admin_id' => $res));
    }

    //设置
    // function set($admin_id, $data) {
    //     //检查权限
    //     if (!$this->userId) {
    //         return array(state => 0, errormsg => '请登录');
    //     }
    //     //查找admin存在
    //     $admin_id = (int) $admin_id;
    //     if (!$admin_id) {
    //         return array(state => 0, errormsg => 'admin id incorrect');
    //     }
    //     $where = array(
    //         'ADMIN_ID' => $admin_id,
    //         );
    //     $res = M(admin)->where($where)->find();
    //     if (!$res) {
    //         return array(state => 0, errormsg => 'admin not found');
    //     }
    //     //获取class
    //     $classId = (int) $res['class'];
    //     if (!($this->chief) && !$this->isUltimate($classId)) {
    //         return array(state => 0, errormsg => 'authority incorrect');
    //     }
    //     foreach ($this->config as $key => $value) {
    //         if ($value[id] == $classId) {
    //             $config = $value;
    //             break;
    //         }
    //     }
    //     $setting = $config[setting];
    //     foreach ($data as $key => $value) {
    //         if (array_key_exists($key, $setting)) {
    //             $setting_id = $setting[$key];
    //         } else {
    //             return array(state => 0, errormsg => 'key incorrect');
    //         }
    //         $add = array(
    //             'ADMIN_ID' => $admin_id,
    //             'KEY_ID' => $setting_id,
    //             'CONTENT' => $value,
    //             'CREATE_TIME' => time(),
    //             'CREATOR' => $this->userId,
    //             'STATE' => 1,
    //             );
    //         break;
    //     }
    //     if (!$add) {
    //         return array(state => 0, errormsg => 'data incorrect');
    //     }
    //     $res = M(admin_setting)->add($add);
    //     if (!$res) {
    //         return array(state => 0, errormsg => 'database save error');
    //     }
    //     return array(state => 1, errormsg => 'ok');
    // }
    function ultimate($admin_id, $isUltimate) {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $admin_id = (int) $admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'admin id incorrect');
        }
        //查找admin存在
        $where = array(
            'admin_id' => $admin_id,
            );
        $res = db('admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        $classId = (int) $res['class'];
        $ultimate = $res['ultimate'];
        $save = array("ultimate" => $isUltimate, 'ultimate_admin_id' => $this->userId,'ultimate_time'=>time());
        $res = db('admin')->where($where)->update($save);
        if (!$res) {
            return array('state' => 1, 'errormsg' => 'database save nothing');
            // return array('state' => 0, 'errormsg' => 'database save error');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id,$classId);
        //
        $set = $isUltimate ? 'set' : 'cancel';
        return array('state' => 1, 'tag' => $tag, 'errormsg' => "ultimate $set success");
    }

    function seal($admin_id, $isSeal) {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //查找admin存在
        $admin_id = (int) $admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'admin id incorrect');
        }
        $where = array(
            'admin_id' => $admin_id,
            'state'    => ["<>",$this->state_removed],
            );
        $res = db('admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        //        if(!$res[seal] && !$cancel){
        //            return array(state=>0,errormsg=>'already sealed');
        //        }
        //        if($res[seal] && $cancel){
        //            return array(state=>0,errormsg=>'not sealed');
        //        }
        $targetUserId = $res['user_id'];
        $targetIsUltimate = (boolean) $res['ultimate'];
        //不能封锁自己
        if (!$this->chief && $this->userId == $targetUserId) {
            return array('state' => 0, 'errormsg' => 'authority incorrect(self)');
        }
        //获取class
        $classId = (int) $res['class'];
        if (!$this->chief && ($targetIsUltimate || !$this->isUltimate($classId))) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $state_result = $isSeal ? $this->state_sealed : $this->state_active;
        $save = array(
            'state' => $state_result,
            'seal'          => $isSeal,
            'seal_admin_id' => $this->userId,
            'seal_time' => time(),
            );
        $res = db('admin')->where($where)->update($save);
        if (!$res) {
            return array('state' => 1, 'errormsg' => 'database save nothing');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id,$classId);
        //
        $seal = $isSeal ? 'seal' : "cancel";
        return array('state' => 1, 'tag' => $tag, 'errormsg' => $seal . ' success');
    }

    //移除
    function remove($admin_id) {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //查找admin存在
        $admin_id = (int) $admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'admin id incorrect');
        }
        $where = array(
            'admin_id' => $admin_id,
                // 'STATE'         => $this->state_active,
            );
        $res = db('admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        if (!isset($res['state']) || !$res['state']) {
            return array('state' => 0, 'errormsg' => 'already removed');
        }
        $targetUserId = $res['user_id'];
        $targetIsUltimate = (boolean) $res['ultimate'];
        //不能删除自己
        if (!$this->chief && $this->userId == $targetUserId) {
            return array('state' => 0, 'errormsg' => 'authority incorrect(self)');
        }
        //获取class
        $classId = (int) $res['class'];
        if (!$this->chief && ($targetIsUltimate || !$this->isUltimate($classId))) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $save = array('state' => 0);
        $res = db('admin')->where($where)->update($save);
        if (!$res) {
            // return array('state' => 1, 'errormsg' => 'database save nothing');
            return array('state' => 1, 'errormsg' => 'database save nothing');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id,$classId);
        //
        return array('state' => 1, 'tag' => $tag, 'errormsg' => 'remove success');
    }

    //列表
    function get_list($filter = []) {
        //        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief && !$this->ultimate) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $config = $this->config;
        if (!$config) {
            return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>101);
            // return array(state => 0, errormsg => 'config incorrect',from=>admin);
        }
        foreach ($config as $key => $value) {
            if($this->isUltimate($key)){
                $list[$value['id']] = ['class_name'=>$value['name']]; //$list[$value['id']] = ['class_name'=>strtoupper($key)];
                $classIds[] = $value['id'];
            }
        }
        // dump($classIds);
        // dump($list);
        $where = ['state'=>["<>",$this->state_removed],'class'=>['in',$classIds]];
        $order = 'seal asc,ultimate desc,create_time desc';
        $res = db('admin')->where($where)->order($order)->select();
        // dump($res);
        $userIds = [];
        foreach ($res as $key => $value) {
            $value['create_time'] = timeString($value['create_time']);
            if($value['ultimate_time']) $value['ultimate_time'] = timeString($value['ultimate_time']);
            if($value['seal_time']) $value['seal_time'] = timeString($value['seal_time']);
            $classId = $value['class'];
            $list[$classId]['users'][] = $value;
            $userId = $value['user_id'];
            if($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['creator'];
            if($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['seal_admin_id'];
            if($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['ultimate_admin_id'];
            if($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
        }
        if(count($userIds)){
            // dump($userIds);
            $user = $this->user;
            $users = $user->getInfoById($userIds);
            // return ['state'=>1,'data'=>['list'=>$list]];
            $res = db('user_tel')->where(['state'=>1,'user_id'=>['in',$userIds]])->select();
            foreach ($res as $k => $v) {
                $tels[$v['user_id']] = $v['tel'];
            }
            $res = db('user_email')->where(['state'=>1,'user_id'=>['in',$userIds]])->select();
            foreach ($res as $k => $v) {
                $emails[$v['user_id']] = $v['email'];
            }
            // dump($users);
            // dump($list);
            foreach ($list as $key => $value) {
                if(!isset($value['users'])){ continue; }
                foreach ($value['users'] as $k => $v) {
                    $user_id = $v['user_id'];
                    $user = $users[$user_id];
                    $list[$key]['users'][$k]['user_name'] = (isset($user['set_name'])&&$user['set_name'])?$user['set_name']:$user['user_name'];
                    $list[$key]['users'][$k]['headimgurl'] = $user['headimgurl'];
                    if(isset($tels[$user_id])) $list[$key]['users'][$k]['tel'] = $tels[$user_id];
                    if(isset($emails[$user_id])) $list[$key]['users'][$k]['email'] = $emails[$user_id];
                    $creator = $users[$v['creator']];
                    $list[$key]['users'][$k]['creator_name'] = isset($creator['set_name'])&&$creator['set_name']?$creator['set_name']:$creator['user_name'];
                    if($v['seal_admin_id']){
                        $seal_admin = $users[$v['seal_admin_id']];
                        $list[$key]['users'][$k]['seal_admin_name'] = isset($seal_admin['set_name'])&&$seal_admin['set_name']?$seal_admin['set_name']:$seal_admin['user_name'];
                    }
                    if($v['ultimate_admin_id']){
                        $ultimate_admin = $users[$v['ultimate_admin_id']];
                        $list[$key]['users'][$k]['ultimate_admin_name'] = isset($ultimate_admin['set_name'])&&$ultimate_admin['set_name']?$ultimate_admin['set_name']:$ultimate_admin['user_name'];
                    }
                }
            }
        }
        return ['state'=>1,'data'=>['list'=>$list]];

    }

    function list_option() {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        $config = $this->config;
        if (!$config) {
            return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>'admin2');
        }
        foreach ($config as $key => $value) {
            if ($this->chief || $this->isUltimate($key)) {
                $filter[] = $value['name'];
//                $filter[] = $key;
            }
        }
        if (!isset($filter)) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        return array('state' => 1, 'data' => array('rank' => $filter));
    }

    function menu() {
        $user_id = $this->userId;
        if(!$user_id) return['errormsg'=>'请登录'];
        $config = getConfig('admin');
        if(!$config) return['errormsg'=>'config error','errorcode'=>'am91294'];
        $chief = $this->chief;
        if($chief || $this->isUltimate()) $rank[] = 'manage';
        foreach ($config as $key => $value) {
            $is = $this->is($key);
            if ($chief || (isset($is['state']) && $is['state']) ) {
                $rank[] = $key;
            }
        }
        if(!isset($rank)) return['errormsg'=>'not admin'];
        return ['state'=>1,'data'=>['rank'=>$rank]];
    }
    function exist($user_id = 0){
        if(!$user_id) return false;
        $where = ['user_id'=>$user_id,'state'=>$this->state_active];
        $res = db('admin')->where($where)->find();
        if($res) return true;
        else{return false;}
    }
    //通用
    function is($demand, $isUltimate = false, $user_id = 0) {
        if(!$user_id) $user_id = $this->userId;
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand','errorcode'=>'admin43642246');
        }
        //检查权限
        if (!$user_id) {
            return array('state' => 0, 'errormsg' => 'user_id missing','errorcode'=>'admin56235235');
        }
        $config = $this->config;
        if (!isset($config)) {
            return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>103);
            // return array(state => 0, errormsg => 'config incorrect');
        }
        //class id号输入
        if($demand == "ultimate"){
            if($this->isUltimate(null,$user_id)){
                return array('state' => 1,'ultimate'=>1);
            }
            if($this->isChief($user_id)){
                return array('state' => 1,'chief'=>1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        }else{
            if(!array_key_exists($demand,$config)){
                foreach ($config as $key => $value) {
                    if(isset($value['contains'])){
                        $contains = $value['contains'];
                        if(in_array($demand,explode(",",$contains))){
                            $classIds[] = $value['id'];
                        }
                    }
                }
            }else{
                $config = $config[$demand];
                $classId = $config['id'];
            }
            if(!isset($classId) && !isset($classIds)){
                return array('state' => 0, 'errormsg' => 'demand incorrect');
            }
        }
        //看看是否已经添加了管理员
        $where = array(
            'user_id' => $user_id,
            'state' => $this->state_active,
            );
        if(isset($classId)){
            $where['class'] = $classId;
        }
        if(isset($classIds)){
            $where['class'] = ['in',implode(",",$classIds)];//" `CLASS` in (".implode(",",$classIds).") ";
        }
        if ($isUltimate) {
            $where['ultimate'] = 1;
        }
        $res = db('admin')->where($where)->find();
        if (!$res) {
            if($this->isChief($user_id)){
                return array('state' => 1,'chief' => 1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        return array('state' => 1, 'errormsg' => 'is admin');
    }

    // function getSet($demand, $setting) {
    //     if (!$demand) {
    //         return array('state' => 0, 'errormsg' => 'need demand');
    //     }
    //     if (!$setting) {
    //         return array('state' => 0, 'errormsg' => 'need setting');
    //     }
    //     //检查权限
    //     if (!$this->userId) {
    //         return array('state' => 0, 'errormsg' => '请登录');
    //     }
    //     $config = $this->config;
    //     if (!$config) {
    //         return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>104);
    //         // return array(state => 0, errormsg => 'config incorrect');
    //     }
    //     $config = $config[$demand];
    //     $classId = $config[id];
    //     if (!$classId) {
    //         return array('state' => 0, 'errormsg' => 'demand incorrect');
    //     }
    //     if (!array_key_exists($setting, $config[setting])) {
    //         return array(state => 0, errormsg => 'setting incorrect');
    //     }
    //     $setting_id = $config[setting][$setting];
    //     //看看是否已经添加了管理员
    //     $where = array(
    //         'a.USER_ID' => $this->userId,
    //         'a.STATE' => $this->state_active,
    //         'a.CLASS' => $classId,
    //         's.KEY_ID' => $setting_id,
    //         );
    //     $order = array("ADMIN_SETTING_ID desc");
    //     $p = C('DB_PREFIX');
    //     $res = M(admin)
    //     ->alias(a)
    //     ->join($p . "admin_setting AS s ON s.ADMIN_ID = a.ADMIN_ID")
    //     ->where($where)
    //     ->order($order)
    //     ->find();
    //     if (!$res) {
    //         return array(state => 0, errormsg => 'setting not found');
    //     }
    //     return array(state => 1, data => array(content => $res[content]));
    // }

    //获取最高权限管理者列表
    function chiefList() {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        // $config = $this->config;
        // if (!$config) {
            // return array('state' => 0, 'errormsg' => 'config incorrect',from=>admin,errorcode=>105);
            // return array(state => 0, errormsg => 'config incorrect');
        // }
        //获取chief配置文件里的数据
        $chief_ids = getConfig('admin_chief');
        $user = $this->user;
        $info = $user->getInfoById($chief_ids);
        foreach ($info as $key => $value) {
            $user_name = $value['set_name']?$value['set_name']:$value['user_name'];
            $chiefs[] = ['user_name'=>$user_name,'user_id'=>$value['user_id']];
        }
        return ['state'=>1,'data'=>['rank'=>$chiefs]];
    }



    //-------------------------新权限-----------------------------------

    //获取权限列表
    public function getlist()
    {
        //权限检查
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        $admin = db("user_role")->where("user_id = $this->userId")->find();
        if(!$admin) return ['state'=>0,'errormsg'=>'您没有权限'];
        if($admin['super_amdin']){
            //超级管理员,所有权限
            $res = db("role")->where("state = 1")->select();
            if(!$res) ['state'=>0,'errormsg'=>'权限获取失败'];
            $res = recursion($res,0);
            return ['state'=>1,'list'=>$res];
        }
        //获取普通管理员权限列表
        if($admin['role_id']){
            $res = db("role")->where("state = 1 and role_id in ($admin[role_id])")->select();
            if(!$res) ['state'=>0,'errormsg'=>'权限获取失败'];
            $res = recursion($res,0);
            return ['state'=>1,'list'=>$res];
        }
        return ['state'=>0];
    }
    //根据接口查找权限
    public function isAdmin($demand,$action){
        if(!$this->userid) return ['state'=>0,'errormg'=>'请登录'];
        if(!$demand) return ['state'=>0,'errormsg'=>'参数错误'];
        if(!$action) return ['state'=>0,'errormsg'=>'方法错误'];
        $path = '/'.$demand.'_admin/'.$action;
        //获取当前用户有的权限
        $role = db("user_role")->where("state = 1 and user_id = 87")->find();
        if(!$role) return ['state'=>0,'errormsg'=>'您没有权限'];
        $role_id = $role['role_id'];
        //获取权限列表
        $rolelist = db("role")->where("role_id in ($role_id) and state = 1 and rank !=0 and path like '%$path%'")->select();
        if(!$rolelist) return ['state'=>0,'errormsg'=>'您没有权限'];
        return ['state'=>1];
    }
    //添加权限
    public function addNew($user_id,$role_id)
    {
        if(!$user_id) return ['state'=>0,'errormsg'=>'请选择用户'];
        if(!$role_id) return ['state'=>0,'errormsg'=>'请选择权限'];
        //取出用户当前的权限
        $role = db("user_role")->where("state = 1")->find();
        if($role){
            //新添加权限
            //判断权限
            $roleids = explode(',',$role_id);
            foreach ($roleids as $k =>$v){
                $a = db("role")->field("role_id,rank")->where("role_id = $v and state = 1")->find();
                if(!$a) return ['state'=>0,'errormsg'=>'权限选择错误,请重试'];
                if($a['rank'] == 0){
                    isset($role_id) ? $role_id .=','.$a['role_id'] : $role_id = $a['role_id'];
                }else{
                    $p = db("role")->field("role_id,rank")->where("state = 1 and role_id = $a[rank]")->find();
                    isset($role_id) ? $role_id .=','.$p['role_id'] : $role_id = $p['role_id'];
                }
            }
            $role_id = implode(',',array_unique(explode(',',$role_id)));
            $data['state'] = 1;
            $data['admin_user_id'] = $this->userId;
            $data['create_time'] = time();
            $data['role_id'] = $role_id;
            $data['user_id'] = $user_id;
            $res = db("user_role")->insert($data);
            if(!$res) return ['state'=>0,'errormsg'=>"设置失败,请重试"];
            return ['state'=>1];
        }
        //获取以前的权限,去重
        $roleId = db("user_role")->field("role_id")->where("state = 1 and user_id = $user_id")->find();
        if($roleId['role_id']){
            $role_id = $role_id.','.$roleId;
        }
        $roleids = explode(',',$role_id);
        foreach ($roleids as $k =>$v){
            $a = db("role")->field("role_id,rank")->where("role_id = $v and state = 1")->find();
            if(!$a) return ['state'=>0,'errormsg'=>'权限选择错误,请重试'];
            if($a['rank'] == 0){
                isset($role_id) ? $role_id .=','.$a['role_id'] : $role_id = $a['role_id'];
            }else{
                $p = db("role")->field("role_id,rank")->where("state = 1 and role_id = $a[rank]")->find();
                isset($role_id) ? $role_id .=','.$p['role_id'] : $role_id = $p['role_id'];
            }
        }
        $role_id = implode(',',array_unique(explode(',',$role_id)));
        $res = db("user_role")->where("user_id = $user_id and state = 1")->update(['role_id'=>$role_id]);
        if(!$res) return ['state'=>0,'errormsg'=>'设置失败,请重新设置'];
        return ['state'=>1];
    }
    //删除权限
    public function removeNew($user_id,$role_id)
    {
        if(!$user_id) return ['state'=>0,'errormsg'=>'请选择用户'];
        if(!$role_id) return ['state'=>0,'errormsg'=>'请选择权限'];
        //取出用户当前的权限
        $role = db("user_role")->where("state = 1 and user_id = $user_id")->find();
        if(!$role) return ['state'=>0,'errormsg'=>'该用户没有权限'];
        //获取权限
        $roleids = explode(',',$role_id);
        foreach ($roleids as $k =>$v){
            $a = db("role")->field("role_id,rank")->where("role_id = $v and state = 1")->find();
            if(!$a) return ['state'=>0,'errormsg'=>'权限选择错误,请重试'];
            if($a['rank'] == 0){
                isset($role_id) ? $role_id .=','.$a['role_id'] : $role_id = $a['role_id'];
            }else{
                $p = db("role")->field("role_id,rank")->where("state = 1 and role_id = $a[rank]")->find();
                isset($role_id) ? $role_id .=','.$p['role_id'] : $role_id = $p['role_id'];
            }
        }
        $role_id = array_unique(explode(',',$role_id));
        //取出用户的权限
        $roleId = explode(',',$role['role_id']);
        foreach ($role_id as $k =>$v){
            foreach ($roleId as $kk =>$vv){
                if($v == $vv){
                    unset($roleId[$k]);
                }
            }
        }
        $role_id = implode($roleId);
        $data['role_id'] = $role_id;
        $res = db("user_role")->where("state = 1 and user_id = $user_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'删除失败,请重试'];
        return ['state'=>1];
    }
}
